package cn.my.framework.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.*;
import java.io.IOException;

/**
 * Created by zhangl_lc on 2017/7/4.
 */
@Configuration
public class MyWebConfiguration  extends WebMvcConfigurerAdapter
        implements EnvironmentAware,ApplicationContextAware {

    Logger logger = LoggerFactory.getLogger(MyWebConfiguration.class);

    private Environment environment;
    public static ApplicationContext context = null;

    /**
     * 提前加载Environment，防止注入失败
     */
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    /**
     * 自动注入ApplicationContext
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    //@Bean
    public FilterRegistrationBean myFilterRegistration(){
        logger.debug("设置自定义过滤器");
        FilterRegistrationBean fReg = new FilterRegistrationBean();
        fReg.setFilter(new MyFilter());
        fReg.setName("myFilter");
        fReg.addUrlPatterns("/*");
        return fReg;
}

    public class MyFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {}

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            //logger.debug(">>>>> remote=[{}],local=[{}]",request.getRemoteAddr(),request.getLocalAddr());
            chain.doFilter(request,response);
        }

        @Override
        public void destroy() {

        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/layui/**").addResourceLocations("classpath:/static/layui2/");
        super.addResourceHandlers(registry);
    }

    /*跨域配置*/
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/rest/**");
    }
}
